(function($) {
    $.fn.random = {};
    $.fn.random.initial = function() {
        getAllData();
        bindQuestion();
        bindRadio();
        bindLiClick();
        bindResult();
        setInterval(timeshow, 1000);
    };
    $.fn.random.num = 0;
    $.fn.random.maxnum = 0;
    $.fn.random.data = {};
    $.fn.random.answer = '';
    $.fn.random.record={'num':0,'right':0,'wrong':0,'score':0};
    $.fn.random.record.type1={'num':0,'right':0,'wrong':0};
    $.fn.random.record.type2={'num':0,'right':0,'wrong':0};
    $.fn.random.record.type3={'num':0,'right':0,'wrong':0};
    $.fn.random.record.type4={'num':0,'right':0,'wrong':0};
    $.fn.random.record.type5={'num':0,'right':0,'wrong':0};
    var bindAnswer = function() {
        $('.answer').on('click', 'button', function() {
            $('.explain-answer').slideToggle();
        });
    };
    var bindLiClick = function() {
        var questionbody = $('#p_data');
        questionbody.on('click', 'li', function(event) {
            if (event.target.nodeName.toLowerCase() != 'input')
                $(this).find('input[type="radio"]').click();
        });
    };
    var bindResult=function(){
        $('#result').on('click',function(){
            $('#resultSubject').text("结果");
            var strResult="<p><img src='i/total.png' style='margin:0 5px 5px 0;'>总共题目："+$.fn.random.maxnum+'</p>'+
                            "<p><img src='i/done.png' style='margin:0 5px 5px 0;'>已做题目："+$.fn.random.record['num']+'</p>'+
                            "<p><img src='i/wrong.png' style='margin:0 5px 5px 0;'>做错题目："+$.fn.random.record['wrong']+'</p>';
             $('#resultBody').html(strResult);               
            $('#my-popup').modal();
        });
    };
    var timeshow = function() {
        var time = new Date();
        $('#hour_show').text(time.getHours());
        $('#minute_show').text(time.getMinutes());
        if (time.getHours() < 10) {
            $('#hour_show').text('0' + time.getHours());
        } else
            $('#hour_show').text(time.getHours());
        if (time.getMinutes() < 10) {
            $('#minute_show').text('0' + time.getMinutes());
        } else
            $('#minute_show').text(time.getMinutes());
        if (time.getSeconds() < 10) {
            $('#second_show').text('0' + time.getSeconds());
        } else
            $('#second_show').text(time.getSeconds());
    };
    var bindQuestion = function() {
        $('#showAnswer').on('click', function() {

            $('#explain-answer').html($.fn.random.answer);
        });
        $('#preQuestion').on('click', function() {
            $.fn.random.num = $.fn.random.num - 1;
            if ($.fn.random.num < 0)
                $.fn.random.num = 0;
            setContentFromData($.fn.random.data);
        });
        $('#nextQuestion').on('click', function() {
            checkAnswer();
            $.fn.random.num = $.fn.random.num + 1;
            $.fn.random.record['num']=$.fn.random.record['num']+1;
            if ($.fn.random.num > $.fn.random.maxnum - 1)
                $.fn.random.num = $.fn.random.maxnum - 1;
            setContentFromData($.fn.random.data);
        });

    };
    var checkAnswer = function() {

        if ($.fn.random.data[$.fn.random.num].type == 2) {
            var option = $("[name='radio-1']").filter(":checked");
            if (option != undefined) {
                var answer = $.fn.random.data[$.fn.random.num]['answer2'];
                if (answer != option.val()) {
                    $.fn.random.record['wrong']=$.fn.random.record['wrong']+1;
                    showError('回答错误','正确答案是 ' + answer);
                
                }
            }

        }
    };
    var showError=function(title,content){
        $('#modal-title').text(title);
        $('#modal-body').text(content);
        $('#myModal').modal();
    };
    var bindRadio = function() {
        $("[name='radio-1']").on('click', function() {
            var option = $("[name='radio-1']").filter(":checked");
            alert(option.val());
        });
    };
    var getAllData = function() {
        $('#my-modal-loading').modal();
        $.ajax({
            url : "db/getAll",
            type : 'get',
            dataType : 'json',
            timeout:5000,
            contentType : 'application/json;charset=utf-8',
            success : function(data) {
                $('#my-modal-loading').modal('close');
                if (data['status'] == '1001') {
                    setContentFromData(data['body']);
                    $.fn.random.data = data['body'];
                }
            },
            error:function(){
                $('#my-modal-loading').modal('close');
                alert('请求超时,重新请求...');
                getAllData();
            }
        });
    };
    var setContentFromData = function(data) {
        $('#explain-answer').html('');
        var length = data.length;
        $('#totalQuestion').text('/' + length);
        $('#questionLocation').text($.fn.random.num + 1);
        if (length != null || length != undefined) {
            $.fn.random.maxnum = length;
        }
        var question = data[$.fn.random.num]['question'].replace(/\ +/g, '_________');
        console.log(question);

        console.log(question);
        if (data[$.fn.random.num]['type'] == 1) {

            $('#question').text(question);
            $('#p_data ul').hide();
            $.fn.random.answer = data[$.fn.random.num]['answer1'];
        }

        if (data[$.fn.random.num]['type'] == 2) {
            $('#question').text(question);
            $('#p_data1').html('');
            $('#p_data ul').show();
            $('#p_data ul').html('');
             $.fn.random.answer=data[$.fn.random.num]['answer2'];
            var options = data[$.fn.random.num]['options'].split('|');
            for (var i = 0; i < options.length; i++) {
                var value = options[i];
                if(value.trim()=='')
                return;
                var optionvalue = '';
                switch(i) {
                case 0:
                    option = 'A. ' + value;
                    optionvalue = 'A';
                    break;
                case 1:
                    option = 'B. ' + value;
                    optionvalue = 'B';
                    break;
                case 2:
                    option = 'C. ' + value;
                    optionvalue = 'C';
                    break;
                case 3:
                    option = 'D. ' + value;
                    optionvalue = 'D';
                    break;
                }
                var li = $('<li></li>');
                var body = $('#p_data ul');
                li.append('<input type="radio" style="padding-top:10px" name="radio-1" value=' + optionvalue + '> ' + option + ' ');
                body.append(li);
            }

        }

    };
})(jQuery);
